// 后端认证服务 - 使用PostgreSQL数据库
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { pool } = require('../../src/config/database');

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

class AuthService {
  // 管理员登录
  async adminLogin(credentials) {
    const { email, password } = credentials;

    try {
      // 由于现有admins表没有email字段，我们使用username作为登录标识
      // 这里的email参数实际上会被当作username使用
      const result = await pool.query(
        'SELECT id, username, password FROM admins WHERE username = $1',
        [email] // 前端传入的email实际上是username
      );

      if (result.rows.length === 0) {
        return {
          success: false,
          message: '用户名或密码错误'
        };
      }

      const admin = result.rows[0];

      // 验证密码 - 现有表中密码字段名为password，可能是明文或已加密
      // 先尝试直接比较，如果不匹配再尝试bcrypt比较
      let isValidPassword = false;

      if (admin.password === password) {
        // 明文密码匹配
        isValidPassword = true;
      } else {
        // 尝试bcrypt比较
        try {
          isValidPassword = await bcrypt.compare(password, admin.password);
        } catch (bcryptError) {
          // 如果bcrypt比较失败，说明可能是明文密码但不匹配
          isValidPassword = false;
        }
      }

      if (!isValidPassword) {
        return {
          success: false,
          message: '用户名或密码错误'
        };
      }

      // 生成JWT token
      const token = jwt.sign(
        { userId: admin.id, username: admin.username, isAdmin: true },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      return {
        success: true,
        data: {
          token,
          user: {
            id: admin.id,
            username: admin.username,
            email: admin.username + '@admin.local', // 生成一个虚拟邮箱
            role: 'admin',
            isAdmin: true
          }
        }
      };
    } catch (error) {
      console.error('管理员登录失败:', error);
      return {
        success: false,
        message: '登录失败'
      };
    }
  }

  // 用户注册
  async register(userData) {
    const { username, email, password } = userData;

    try {
      // 检查用户是否已存在
      const existingUser = await pool.query(
        'SELECT id FROM users WHERE email = $1 OR username = $2',
        [email, username]
      );

      if (existingUser.rows.length > 0) {
        throw new Error('用户名或邮箱已存在');
      }

      // 加密密码
      const saltRounds = 10;
      const passwordHash = await bcrypt.hash(password, saltRounds);

      // 创建用户
      const result = await pool.query(
        `INSERT INTO users (username, email, password_hash) 
         VALUES ($1, $2, $3) 
         RETURNING id, username, email, avatar_url, created_at`,
        [username, email, passwordHash]
      );

      const user = result.rows[0];

      // 生成JWT token
      const token = jwt.sign(
        { userId: user.id, email: user.email },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      return {
        success: true,
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            avatar_url: user.avatar_url
          }
        }
      };
    } catch (error) {
      console.error('注册失败:', error);
      return {
        success: false,
        message: error.message || '注册失败'
      };
    }
  }

  // 用户登录
  async login(credentials) {
    const { email, password } = credentials;

    try {
      // 查找用户
      const result = await pool.query(
        'SELECT id, username, email, password_hash, avatar_url FROM users WHERE email = $1',
        [email]
      );

      if (result.rows.length === 0) {
        return {
          success: false,
          message: '邮箱或密码错误'
        };
      }

      const user = result.rows[0];

      // 验证密码
      const isValidPassword = await bcrypt.compare(password, user.password_hash);

      if (!isValidPassword) {
        return {
          success: false,
          message: '邮箱或密码错误'
        };
      }

      // 生成JWT token
      const token = jwt.sign(
        { userId: user.id, email: user.email },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      return {
        success: true,
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            avatar_url: user.avatar_url
          }
        }
      };
    } catch (error) {
      console.error('登录失败:', error);
      return {
        success: false,
        message: '登录失败'
      };
    }
  }

  // 验证token并获取用户信息
  async verifyToken(token) {
    try {
      // 检查token是否为空或无效格式
      if (!token || token === 'null' || token === 'undefined' || typeof token !== 'string') {
        return {
          success: false,
          message: 'Token格式无效'
        };
      }

      // 验证JWT token
      const decoded = jwt.verify(token, JWT_SECRET);

      // 检查decoded payload是否包含必要信息
      if (!decoded.userId) {
        return {
          success: false,
          message: 'Token payload无效'
        };
      }

      // 如果是管理员token，直接返回管理员信息
      if (decoded.isAdmin) {
        return {
          success: true,
          data: {
            id: decoded.userId,
            username: decoded.username,
            email: decoded.username + '@admin.local',
            role: 'admin',
            isAdmin: true
          }
        };
      }

      // 普通用户，从数据库查询用户信息
      const result = await pool.query(
        'SELECT id, username, email, avatar_url FROM users WHERE id = $1',
        [decoded.userId]
      );

      if (result.rows.length === 0) {
        return {
          success: false,
          message: '用户不存在'
        };
      }

      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('Token验证失败:', error);

      // 根据不同的JWT错误类型返回不同的消息
      if (error.name === 'JsonWebTokenError') {
        return {
          success: false,
          message: 'Token格式错误'
        };
      } else if (error.name === 'TokenExpiredError') {
        return {
          success: false,
          message: 'Token已过期'
        };
      } else if (error.name === 'NotBeforeError') {
        return {
          success: false,
          message: 'Token尚未生效'
        };
      } else {
        return {
          success: false,
          message: 'Token验证失败'
        };
      }
    }
  }

  // 更新用户信息
  async updateProfile(userId, userData) {
    const { username, avatar_url } = userData;

    try {
      const result = await pool.query(
        `UPDATE users 
         SET username = $1, avatar_url = $2, updated_at = CURRENT_TIMESTAMP
         WHERE id = $3
         RETURNING id, username, email, avatar_url`,
        [username, avatar_url, userId]
      );

      if (result.rows.length === 0) {
        throw new Error('用户不存在');
      }

      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return {
        success: false,
        message: error.message || '更新失败'
      };
    }
  }

  // 修改密码
  async changePassword(userId, passwordData) {
    const { currentPassword, newPassword } = passwordData;

    try {
      // 获取当前密码哈希
      const result = await pool.query(
        'SELECT password_hash FROM users WHERE id = $1',
        [userId]
      );

      if (result.rows.length === 0) {
        throw new Error('用户不存在');
      }

      const user = result.rows[0];

      // 验证当前密码
      const isValidPassword = await bcrypt.compare(currentPassword, user.password_hash);

      if (!isValidPassword) {
        return {
          success: false,
          message: '当前密码错误'
        };
      }

      // 加密新密码
      const saltRounds = 10;
      const newPasswordHash = await bcrypt.hash(newPassword, saltRounds);

      // 更新密码
      await pool.query(
        'UPDATE users SET password_hash = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',
        [newPasswordHash, userId]
      );

      return {
        success: true,
        message: '密码修改成功'
      };
    } catch (error) {
      console.error('修改密码失败:', error);
      return {
        success: false,
        message: error.message || '修改密码失败'
      };
    }
  }
}

module.exports = new AuthService();